package com.cloudfun.campusshare.code.generate.definition;

import lombok.Data;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * Created by Huqin on 2020/5/27
 */
@Data
public class AnnotationDefinition {
    private final Class clazz;
    private final Map<String, Object> attrs = new HashMap<>();

    public AnnotationDefinition(Class clazz) {
        this.clazz = clazz;
    }

    public void addAttr(String name, Object val) {
        attrs.put(name, val);
    }

    public String getClassName() {
        return clazz.getName();
    }

    public String getSimpleName() {
        return clazz.getSimpleName();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder().append("@");
        sb.append(getSimpleName());


        if (MapUtils.isNotEmpty(attrs)) {
            sb.append("(");
            if (attrs.size() == 1 && attrs.entrySet().stream().findFirst().get().getKey().equals("value")) {
                sb.append(parseValue(attrs.entrySet().stream().findFirst().get().getValue()));
            } else {
                List<String> fields = new ArrayList<>();
                for (Map.Entry<String, Object> entry : attrs.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    String valueStr = parseValue(value);
                    fields.add(key + " = " + valueStr);
                }
                sb.append(StringUtils.join(fields, ", "));
            }
            sb.append(")");
        }
        return sb.toString();
    }

    private static String parseValue(Object value) {
        if (value instanceof String) {
            // 字符串或其他类型
            return "\"" + value + "\"";
        } else {
            return value.toString();
        }
    }
}
